package com.zw.yzk.kabu.data.repository;

import android.content.Context;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.store.GoodsStore;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.GoodsListEntity;
import com.zw.yzk.kabu.data.network.service.GoodsListService;
import com.zw.yzk.kabu.data.network.task.GoodsListTask;
import com.zw.yzk.kabu.data.utils.NetworkUtils;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/2/27.
 */

public class GoodsListRepository extends CommonRepository {

    @Inject
    GoodsStore goodsStore;
    private int totalCount;
    private Context context;

    @Inject
    public GoodsListRepository(Context context) {
        totalCount = GoodsListTask.DEFAULT_COUNT_PER_PAGE;
        this.context = context;
    }

    @Override
    protected Observable commonObserve(Task task) {
        if (((GoodsListTask) task).getLocal) {
            if (!NetworkUtils.isConnected(context)) {
                return Observable.just(goodsStore.getGoodsList());
            }
            return Observable.concat(Observable.just(goodsStore.getGoodsList()), super.commonObserve(task));
        } else {
            return super.commonObserve(task);
        }
    }

    @Override
    protected Observable connectServer(Task task) {
        GoodsListService service = ServiceGenerator.createService(GoodsListService.class);
        GoodsListTask goodsListTask = (GoodsListTask) task;
        if(goodsListTask.isSearch) {
            goodsListTask.start = 0;
            goodsListTask.size = 20;
            totalCount = goodsListTask.size;
        }

        if (goodsListTask.start >= totalCount) {
            GoodsListEntity entity = new GoodsListEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.total = totalCount;

            return Observable.just(entity);
        } else {
            //加载网络数据
            return service.getGoodsList(
                    goodsListTask.start,
                    goodsListTask.size,
                    goodsListTask.keyWord,
                    goodsListTask.subType,
                    goodsListTask.userId,
                    goodsListTask.accessToken);
        }
    }

    @Override
    protected Func1<GoodsListEntity, Observable> getServerData() {
        return new Func1<GoodsListEntity, Observable>() {
            @Override
            public Observable call(GoodsListEntity entity) {
                totalCount = entity.result.total;

                return Observable.just(entity);
            }
        };
    }

}
